package com.weai.service;

import com.weai.entity.Task;
import com.weai.repository.TaskRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.List;

import static org.apache.commons.lang3.BooleanUtils.forEach;

@Service
@Slf4j
public class ScheduleBackTasksDetail {


    private final TaskRepository taskRepository;

    public ScheduleBackTasksDetail(TaskRepository taskRepository) {
        this.taskRepository = taskRepository;
    }

    //每周一0点执行
    @Scheduled(cron = "0 0 0 * * MON")
    //每一分钟执行
//    @Scheduled(cron = "0 * * * * ?")
    public void scheduleBackTasksDetail() {
        log.info("开始执行定时任务，更新任务，将每个任务的下周计划，填写到本周任务中");
        // 设置当前周的周一和周日日期
        LocalDate now = LocalDate.now();
        LocalDate startOfWeek = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

        // 上周的周一和周日日期
        LocalDate startOfLastWeek = startOfWeek.minusWeeks(1);
        LocalDate endOfLastWeek = endOfWeek.minusWeeks(1);

        // 查询所有period_end_date是上周的任务
        List<Task> allByPeriodEndDateBetween = taskRepository.findAllByPeriodEndDateBetween(startOfLastWeek, endOfLastWeek);
        if (allByPeriodEndDateBetween.isEmpty()) {
            log.info("没有需要更新的任务！");
        } else {
            log.info("需要更新的任务数量为：{}", allByPeriodEndDateBetween.size());
            allByPeriodEndDateBetween.forEach(task -> {
                // 更新任务的period_end_date和period_start_date为本周的日期
                task.setPeriodEndDate(endOfWeek);
                task.setPeriodStartDate(startOfWeek);
                // 将上周的任务的next_week_plan字段，填充到本周的任务的this_week_plan字段中，同时将next_week_plan字段清空，id字段也清空，其他字段不变
                task.setThisWeekPlan(task.getNextWeekPlan());
                task.setNextWeekPlan(null);
                task.setId(null);
                // 保存任务
                taskRepository.save(task);
                log.info("任务{},---> {} 的下周计划已更新", task.getId(),task.getTitleIndex());
            });
            log.info("定时任务执行完成,数量为：{}", allByPeriodEndDateBetween.size());
        }
    }

}
